package security.core;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

public class LocalAuthenticationProvider implements AuthenticationProvider{
	
	private static Log LOG = LogFactory.getLog(LocalAuthenticationProvider.class);
	
	 private final List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ADMIN"),
			 															new SimpleGrantedAuthority("USER"));
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
		/*
 		String username= userToken.getName();
		String password = Objects.toString(userToken.getCredentials(), "");
		LOG.info("username: " +  username);
		LOG.info("password: " +  password);
		 */
		//authenticate
		if(this.isMatch(userToken)){
			 return new UsernamePasswordAuthenticationToken(userToken, userToken.getCredentials(), authorities);
		}
		//failue to authenticate for this Authentication provider 
		//spring securtiy then will pass the authenticate to next provider who suit to this authenticate type
		return null;
	}
	
	/**
	 * Define which kind of authentication is suit to this Authentication Provider
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
	}
	
   private boolean isMatch(Authentication authentication){
        if("thomas".equals(authentication.getName()) && "pass".equals(authentication.getCredentials()))
            return true;
        else
            return false;
    }

}
